<template>
  <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>基本资料</span>
  </div>
    <!-- 下面输入表单 -->
    <el-form :model="UserInfo" :rules="RulesInfo" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item  label="原密码" prop="old_pwd">
            <el-input show-password v-model="UserInfo.old_pwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
            <el-input show-password v-model="UserInfo.new_pwd"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_pwd">
            <el-input show-password v-model="UserInfo.re_pwd"></el-input>
        </el-form-item>
         <el-form-item>
            <el-button type="primary" @click="submitForm">修改密码</el-button>
            <el-button @click="$refs.ruleForm.resetFields()">重置</el-button>
        </el-form-item>
    </el-form>
</el-card>
</template>

<script>
export default {
  name: 'UserInfo',
  data() {
      const samePwd = (rule,value,callback) => {
          if (value === this.UserInfo.old_pwd) {
              callback(new Error('新旧密码不能一致'))
          }else{
              callback()
          }
      }

      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.UserInfo.new_pwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
          UserInfo: {
              old_pwd:'',
              new_pwd:'',
              re_pwd:'',
          },
      
        RulesInfo:{
            old_pwd:[
                { required: true, message: '请输入原密码', trigger: 'blur' },
                { pattern: /^\S{6,15}$/, message:'非空字符,长度6-15', trigger:'blur'}
            ],
            new_pwd:[
                { required: true, message: '请输入新密码', trigger: 'blur' },
                { pattern: /^\S{6,15}$/, message:'非空字符,长度6-15', trigger:'blur'},
                { validator: samePwd, trigger: 'blur' }

            ],
            re_pwd:[
                { required: true, message: '请确认新密码', trigger: 'blur' },
                { pattern: /^\S{6,15}$/, message:'非空字符,长度6-15', trigger:'blur'},
                { validator: validatePass, trigger: 'blur' }
            ],
        }
      };
  },
  methods:{
      submitForm(){
          this.$refs.ruleForm.validate(async (valid) => {
            if (!valid) return
           const {data:res} = await this.$axios.patch('/my/updatepwd',this.UserInfo)
        //    debugger
            if(res.code !== 0) return this.$message.error(res.message)

            this.$message.success(res.message)
          
            this.$refs.ruleForm.resetFields()
          })
      
      },
    //   resetForm(){
    //     //   this.UserInfo = {...this.$store.state.userInfo}

    //       this.$refs.ruleForm.resetFields()
    //   }
}
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
